package com.yqya.springboot.mongodb.repository.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.mongodb.client.result.UpdateResult;
import com.yqya.springboot.mongodb.domain.UserInfo;
import com.yqya.springboot.mongodb.repository.UserInfoRepository;

/**
 * 用户信息Repository
 *
 * @author Kevin
 * @date 2019-09-23
 */
@Component
public class UserInfoRepositoryImpl implements UserInfoRepository {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(UserInfo item) {
        mongoTemplate.save(item);
    }

    @Override
    public UserInfo findByUserName(String userName) {
        Query query = new Query(Criteria.where("userName").is(userName));
        UserInfo item = mongoTemplate.findOne(query, UserInfo.class);
        return item;
    }

    @Override
    public Long update(UserInfo item) {
        Query query = new Query(Criteria.where("id").is(item.getId()));
        Update update = new Update().set("userName", item.getUserName()).set("pwd", item.getPwd());
        // 更新查询返回结果集的第一条
        UpdateResult result = mongoTemplate.updateFirst(query, update, UserInfo.class);
        if (result != null) {
            return result.getMatchedCount();
        }
        return 0L;
    }

    @Override
    public void deleteById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, UserInfo.class);
    }

}
